package com.huanwang.commonlibrary.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment

abstract class BaseFragment<A : BaseViewActivityImpl<*>> : Fragment() {
    //初始化布局
    abstract fun onLayoutID(): Int

    //初始化数据
    abstract fun onLoadDate(viewDataBinding: ViewDataBinding)

    //懒加载
    abstract fun onLazyLoad()

    private var mIsFirstVisible: Boolean = true
    private lateinit var dataBinding: ViewDataBinding

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        dataBinding =
            DataBindingUtil.inflate<ViewDataBinding>(inflater, onLayoutID(), container, false)
        val root = dataBinding.root
        return root
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        onLoadDate(dataBinding)
        val isVis = isHidden || userVisibleHint
        if (isVis && mIsFirstVisible) {
            onLazyLoad()
            mIsFirstVisible = false
        }
    }


    /**
     * @desc 此方法只有在不和ViewPager结合的时候才会调用
     * @param
     */
    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!hidden && isResumed()) {
            onLazyLoad()
            mIsFirstVisible = false
        }
    }

    /**
     * 与ViewPager 结合的时候才会调用
     */
    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if (isVisibleToUser && isResumed()) {
            onLazyLoad()
            mIsFirstVisible = false
        }
    }

    open fun getMyActivity(): A? {
        return try {
            activity as A?
        } catch (e: Exception) {
            null
        }
    }
}